#!/bin/bash
cd $(dirname $0)
export g_home_dir=$(pwd)
export g_upload_dir=${g_home_dir}/__UPLOAD__
export g_download_dir=${g_home_dir}/__DOWNLOAD__
export g_plots_dir=${g_download_dir}/PLOTS
. ${g_home_dir}/function_utils.sh

# 校验linux环境
# python version > 2.5
# linux kernel > 2.6
function check_env() {
    mkdir ${g_upload_dir} ${g_download_dir} ${g_plots_dir}
    chmod 777 ${g_upload_dir} ${g_download_dir} ${g_plots_dir}
    local py_path=$(which python 2>/dev/null)
    if [ -z "${py_path}" ]; then
        local py2_path=$(which python2 2>/dev/null)
        local py3_path=$(which python3 2>/dev/null)
        [ -n "${py2_path}" ] && ln -sf ${py2_path} /usr/bin/python
        [ -n "${py3_path}" ] && ln -sf ${py3_path} /usr/bin/python
    fi
    python -c "
import os
import re
import pwd
import sys
import time
import stat
import json
import base64
import threading
import subprocess
"
    local ret=$?
    [ ${ret} -eq 0 ] || echo "missing python environment" >&2
    return ${ret}
}

function init_task() {
    local task=$1
    [ -z "${task}" ] && return 1
    mkdir -p ${task} 2>/dev/null
    chmod 777 ${task} 2>/dev/null
    rm -rf ${task}/* 2>/dev/null

    export g_task_dir=${g_home_dir}/${task}
    cd ${g_task_dir}
    ReportInfo 1
}

function start_task() {
    local task=$1
    local script=$2
    shift 2
    local params=$*
    init_task ${task}
    echo ${script} | grep '.py$' && type='python -u'
    echo "$(whoami): ${type} ${g_home_dir}/${script} ${params}" >${g_task_dir}/${g_call}
    ${type} ${g_home_dir}/${script} ${params} >${g_task_dir}/${g_printout} 2>&1 &
    return $?
}

function stop_task() {
    local task=$1
    local script=$2
    local top_pid=$(ps -ef|grep -w "${script}"|awk '{print $2}'|head -1)
    pstree ${top_pid} -p|tr '(' '\n'|grep '^[0-9]'|cut -d')' -f1|xargs kill
    init_task ${task}
    ReportErr 100 'Stopped'
}

function get_task_progress() {
    local task=$1
    echo "${g_split_flag}"
    cat ${g_home_dir}/${task}/${g_progress}
    echo "${g_split_flag}"
}

function get_task_printout() {
    local task=$1
    echo "${g_split_flag}"
    cat ${g_home_dir}/${task}/${g_printout}
    echo "${g_split_flag}"
}

function get_task_values() {
    local task=$1
    echo "${g_split_flag}"
    cat ${g_home_dir}/${task}/${g_values}
    echo "${g_split_flag}"
}

function auto_download_task() {
    cd ${g_download_dir} || return 1
    chmod -R 777 *
    local dest_file=$(Compress ${g_download_dir} TIMER_DATA)
    if [ $? -eq 0 -a -f "${dest_file}" ]; then
        echo "${g_split_flag}"
        echo "${dest_file}"
        echo "${g_split_flag}"
        return 0
    fi
    echo "Compress ${g_download_dir} failed" >&2
}

$*
exit $?

